package com.chushouya.order.service.admin.impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.response.AlipayOpenAppMiniTemplatemessageSendResponse;
import com.general.framework.core.exception.Ex;
import com.general.framework.core.lang.Strings;
import com.chushouya.manager.service.common.AlipayClientCommonService;
import com.chushouya.order.constants.AlipaySubscribeTemplateEnum;
import com.chushouya.order.constants.OrderStatusEnum;
import com.chushouya.order.dao.entity.OrderEntity;
import com.chushouya.order.dao.entity.OrderExtendEntity;
import com.chushouya.order.dao.repository.OrderExtendRepository;
import com.chushouya.order.dao.repository.OrderRepository;
import com.chushouya.order.service.admin.AlipaySubscribeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * 支付宝订阅消息服务实现类
 * 
 * @author chushouya
 * @date 2025-09-11
 */
@Slf4j
@Service
public class AlipaySubscribeServiceImpl implements AlipaySubscribeService {

    @Resource
    private AlipayClientCommonService alipayClientCommonService;
    
    @Resource
    private OrderRepository orderRepository;

    @Resource
    private OrderExtendRepository orderExtendRepository;

    /**
     * 获取订单信息
     * @param orderId 订单ID
     * @return
     */
    private OrderEntity getOrder(Long orderId) {
        OrderEntity order = orderRepository.selectByPrimaryKey(orderId);
        if (Objects.isNull(order)) {
            throw Ex.business("订单不存在");
        }
        return order;
    }

    /**
     * 获取订单额外信息
     * @param orderId 订单ID
     * @return
     */
    private OrderExtendEntity getOrderExtend(Long orderId) {
        OrderExtendEntity orderExtend = orderExtendRepository.selectByOrderId(orderId);
        if (Objects.isNull(orderExtend)) {
            throw Ex.business("订单扩展信息不存在");
        }
        return orderExtend;
    }

    @Override
    public AlipayOpenAppMiniTemplatemessageSendResponse processSubscribeMessage(Long orderId) {
        log.info("开始处理支付宝订阅消息 - 订单ID: {}", orderId);
        
        try {
            OrderEntity order = getOrder(orderId);
            OrderExtendEntity orderExtend = getOrderExtend(orderId);
            final String openId = orderExtend.getOpenId();
            
            // 根据订单状态决定发送哪种通知
            // 这里可以根据具体业务逻辑调整
            return sendOrderSuccessNotify(orderId);
            
        } catch (Exception e) {
            log.error("处理支付宝订阅消息异常 - 订单ID: {}, 错误: {}", orderId, e.getMessage(), e);
            throw Ex.business("处理支付宝订阅消息失败", e);
        }
    }


    @Override
    public AlipayOpenAppMiniTemplatemessageSendResponse sendOrderSuccessNotify(Long orderId) {
        log.info("发送下单成功订单状态通知 - 订单ID: {}", orderId);
        
        try {
            OrderEntity order = getOrder(orderId);
            OrderExtendEntity orderExtend = getOrderExtend(orderId);
            final String orderNo = order.getOrderNo();
            if (Strings.isBlank(orderExtend.getOpenId())) {
                log.warn("订单缺少支付宝用户ID - 订单ID: {}", orderId);
                return null;
            }
            
            // 构建模板数据 - 订单状态，订单编号，温馨提醒
            JSONObject templateData = new JSONObject();
            
            JSONObject keyword1 = new JSONObject();
            keyword1.put("value", OrderStatusEnum.getDesc(order.getOrderStatus()));
            templateData.put("keyword1", keyword1); // 订单状态
            
            JSONObject keyword2 = new JSONObject();
            keyword2.put("value", order.getOrderNo());
            templateData.put("keyword2", keyword2); // 订单编号
            
            JSONObject keyword3 = new JSONObject();
            keyword3.put("value", "您的订单已成功提交，我们将尽快为您处理");
            templateData.put("keyword3", keyword3); // 温馨提醒

            AlipaySubscribeTemplateEnum template = AlipaySubscribeTemplateEnum.ORDER_SUCCESS;
            String pagePath = Strings.format("{}?orderNo={}", template.getPagePath(), orderNo);
            
            AlipayOpenAppMiniTemplatemessageSendResponse response = alipayClientCommonService.sendMiniTemplateMessage(
                orderExtend.getOpenId(), template.getTemplateId(), pagePath, templateData.toJSONString());
            
            log.info("下单成功通知发送完成 - 订单ID: {}, 结果: {}", orderId, response != null ? "成功" : "失败");
            return response;
            
        } catch (Exception e) {
            log.error("发送下单成功通知异常 - 订单ID: {}, 错误: {}", orderId, e.getMessage());
            throw Ex.business("发送下单成功通知失败", e);
        }
    }

    @Override
    public AlipayOpenAppMiniTemplatemessageSendResponse sendRecycleCancelNotify(Long orderId) {
        log.info("发送回收服务取消通知 - 订单ID: {}", orderId);
        
        try {
            OrderEntity order = getOrder(orderId);
            OrderExtendEntity orderExtend = getOrderExtend(orderId);
            final String orderNo = order.getOrderNo();
            if (Strings.isBlank(orderExtend.getOpenId())) {
                log.warn("订单缺少支付宝用户ID - 订单ID: {}", orderId);
                return null;
            }
            
            // 构建模板数据 - 取消时间，订单编号
            JSONObject templateData = new JSONObject();
            
            JSONObject keyword1 = new JSONObject();
            keyword1.put("value", order.getUpdateTime());
            templateData.put("keyword1", keyword1); // 取消时间
            
            JSONObject keyword2 = new JSONObject();
            keyword2.put("value", order.getOrderNo());
            templateData.put("keyword2", keyword2); // 订单编号
            
            AlipaySubscribeTemplateEnum template = AlipaySubscribeTemplateEnum.RECYCLE_CANCEL;
            String pagePath = Strings.format("{}?orderNo={}", template.getPagePath(), orderNo);
            
            AlipayOpenAppMiniTemplatemessageSendResponse response = alipayClientCommonService.sendMiniTemplateMessage(
                orderExtend.getOpenId(), template.getTemplateId(), pagePath, templateData.toJSONString());
            
            log.info("回收服务取消通知发送完成 - 订单ID: {}, 结果: {}", orderId, response != null ? "成功" : "失败");
            return response;
            
        } catch (Exception e) {
            log.error("发送回收服务取消通知异常 - 订单ID: {}, 错误: {}", orderId, e.getMessage());
            throw Ex.business("发送回收服务取消通知失败 {}", e.getMessage());
        }
    }

    @Override
    public AlipayOpenAppMiniTemplatemessageSendResponse sendPaymentReceivedNotify(Long orderId) {
        log.info("发送回收金额已到账通知 - 订单ID: {}", orderId);
        
        try {
            OrderEntity order = getOrder(orderId);
            OrderExtendEntity orderExtend = getOrderExtend(orderId);
            final String orderNo = order.getOrderNo();
            if (Strings.isBlank(orderExtend.getOpenId())) {
                log.warn("订单缺少支付宝用户ID - 订单ID: {}", orderId);
                return null;
            }
            
            // 构建模板数据 - 回收商品，打款时间，订单编号，订单金额
            JSONObject templateData = new JSONObject();
            
            JSONObject keyword1 = new JSONObject();
            keyword1.put("value", order.getProductName() != null ? order.getProductName() : "回收商品");
            templateData.put("keyword1", keyword1); // 回收商品
            
            JSONObject keyword2 = new JSONObject();
            keyword2.put("value", order.getUpdateTime());
            templateData.put("keyword2", keyword2); // 打款时间
            
            JSONObject keyword3 = new JSONObject();
            keyword3.put("value", order.getOrderNo());
            templateData.put("keyword3", keyword3); // 订单编号
            
            JSONObject keyword4 = new JSONObject();
            keyword4.put("value", "¥" + order.getCompletePrice());
            templateData.put("keyword4", keyword4); // 订单金额
            
            AlipaySubscribeTemplateEnum template = AlipaySubscribeTemplateEnum.PAYMENT_RECEIVED;
            String pagePath = Strings.format("{}?orderNo={}", template.getPagePath(), orderNo);
            
            AlipayOpenAppMiniTemplatemessageSendResponse response = alipayClientCommonService.sendMiniTemplateMessage(
                orderExtend.getOpenId(), template.getTemplateId(), pagePath, templateData.toJSONString());
            
            log.info("回收金额已到账通知发送完成 - 订单ID: {}, 结果: {}", orderId, response != null ? "成功" : "失败");
            return response;
            
        } catch (Exception e) {
            log.error("发送回收金额已到账通知异常 - 订单ID: {}, 错误: {}", orderId, e.getMessage(), e);
            throw Ex.business("发送回收金额已到账通知失败", e);
        }
    }
}
